package com.d3works.apps.hr.db.repo;

import com.d3works.apps.hr.service.app.AppHumanResourceService;
import com.d3works.apps.hr.service.project.ProjectPlanningTimeService;
import com.d3works.apps.project.db.Project;
import com.d3works.apps.project.db.ProjectPlanningTime;
import com.d3works.apps.project.db.ProjectTask;
import com.d3works.apps.project.db.repo.ProjectManagementRepository;
import com.d3works.apps.project.db.repo.ProjectPlanningTimeRepository;
import com.d3works.inject.Beans;
import com.google.inject.Inject;
import java.util.List;

public class ProjectHRRepository extends ProjectManagementRepository {

  @Inject private ProjectPlanningTimeService projectPlanningTimeService;

  @Inject private ProjectPlanningTimeRepository planningTimeRepo;

  @Override
  public Project save(Project project) {
    project = super.save(project);

    if (!Beans.get(AppHumanResourceService.class).isApp("employee")) {
      return project;
    }

    List<ProjectPlanningTime> projectPlanningTimeList =
        planningTimeRepo
            .all()
            .filter("self.project = ?1 OR self.project.parentProject = ?1", project)
            .fetch();

    project.setTotalPlannedHrs(projectPlanningTimeService.getProjectPlannedHrs(project));

    Project parentProject = project.getParentProject();
    if (parentProject != null) {
      parentProject.setTotalPlannedHrs(
          projectPlanningTimeService.getProjectPlannedHrs(parentProject));
    }

    if (projectPlanningTimeList != null) {
      for (ProjectPlanningTime planningTime : projectPlanningTimeList) {
        ProjectTask task = planningTime.getProjectTask();
        if (task != null) {
          task.setTotalPlannedHrs(projectPlanningTimeService.getTaskPlannedHrs(task));
        }
      }
    }

    return project;
  }
}
